# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: jaewon

import logging

from absl import app, flags

from coin.base.datetime_util import to_datetime
from coin.strategy.marketsim.core import spec_pb2
from coin.strategy.marketsim.core.sim_stat import generate_sim_stat
from coin.strategy.marketsim.tool.result_util import read_sim_result


def _aggregate_pnl(sim_results):
  pos_map = {}
  for res in sim_results.values():
    for pos in res.positions:
      if pos.symbol not in pos_map:
        pos_out = spec_pb2.PositionProto()
        pos_out.symbol = pos.symbol
        pos_out.settlement_currency = pos.settlement_currency
        pos_map[pos.symbol] = pos_out
      else:
        pos_out = pos_map[pos.symbol]
      assert pos.symbol == pos_out.symbol
      assert pos.settlement_currency == pos_out.settlement_currency
      pos_out.realized_pnl += pos.realized_pnl + pos.unrealized_pnl
      pos_out.gross_pnl += pos.gross_pnl
      pos_out.gross_fee += pos.gross_fee
  return sorted(pos_map.values(), key=lambda x: x.symbol)


def _aggregate_orders(sim_results):
  orders = []
  for res in sim_results.values():
    orders.extend(res.orders)
  return sorted(orders, key=lambda x: x.submit_ts)


def _aggregate_executions(sim_results):
  orders = []
  for res in sim_results.values():
    orders.extend(res.executions)
  return sorted(orders, key=lambda x: x.submit_ts)


def _aggregate_product_spec(sim_results):
  pspec_out = {}
  for res in sim_results.values():
    for pspec in res.product_specs:
      if pspec.symbol in pspec_out:
        # TODO Check same
        pass
      else:
        pspec_out[pspec.symbol] = pspec
  return sorted(pspec_out.values(), key=lambda x: x.symbol)


def generate_aggregated_sim_stat(sim_results):
  positions = _aggregate_pnl(sim_results)
  orders = _aggregate_orders(sim_results)
  executions = _aggregate_executions(sim_results)
  product_specs = _aggregate_product_spec(sim_results)

  sim_stat = generate_sim_stat(positions, orders, executions, product_specs)
  return sim_stat


def main(args):
  FLAGS = flags.FLAGS
  sim_results = read_sim_result(args[1:])
  agg_sim_stat = generate_aggregated_sim_stat(sim_results)
  print(agg_sim_stat)


if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG',
      format='%(levelname)8s %(asctime)s %(name)s %(filename)s:%(lineno)d] %(message)s')
  app.run(main)
